<template>
    <el-popover v-model="visible" popper-class="popper-style" placement="bottom" width="200" trigger="click">
        <!--  多选框内容 -->
        <div v-if="multiple" slot="reference" class="el-select el-select--small" style="width:100%;">
            <div class="el-select__tags" ref="el_select__tags" style="width: 100%; padding-right:35px;">
                <span>
                    <span v-for="(item,index) in multipleValue" class="el-tag el-tag--info el-tag--mini el-tag--light">
                        <span class="el-select__tags-text">{{ item.name }}</span>
                        <i class="el-tag__close el-icon-close" @click.stop="remove(item,index)"></i>
                    </span>
                </span>
            </div>
            <div class="el-input el-input--small el-input--suffix">
                <input type="text" readonly="readonly" autocomplete="off" :placeholder="multipleValue.length>0?'':'请选择'" class="el-input__inner" :style="{height: inputHeight + 'px'}">
                <span class="el-input__suffix">
                    <span class="el-input__suffix-inner">
                        <i class="el-select__caret el-input__icon el-icon-arrow-up"></i>
                    </span>
                </span>
            </div>
        </div>
        <!--  单选框内容 -->
        <div v-else slot="reference" class="el-select el-select--small" style="width:100%;">
            <div class="el-input el-input--small el-input--suffix">
                <input type="text" readonly="readonly" v-model="singleValue.name" autocomplete="off" placeholder="请选择" class="el-input__inner">
                <span class="el-input__suffix">
                    <span class="el-input__suffix-inner">
                        <i class="el-select__caret el-input__icon el-icon-arrow-up"></i>
                    </span>
                </span>
            </div>
        </div>
        <el-tree ref="deptTree" :data="data" :props="defaultProps" @node-click="handleNodeClick" @check-change="checkChange" node-key="id" :default-checked-keys="defaultKeys" :default-expand-all="true" :show-checkbox="multiple" :check-on-click-node="true">
            <span class="head-folder-icon" slot-scope="{ node, data }">
                <img v-if="!node.expanded && !node.isLeaf " src="@/assets/icons/png/icon-folder.png" alt="">
                <img v-if="node.expanded && !node.isLeaf" src="@/assets/icons/png/icon-folder-opened.png" alt="">
                {{ node.label }}
            </span>
        </el-tree>
    </el-popover>

</template>

<script>
import { treeselect } from '@/api/system/dept'
import { findIndex } from 'lodash'

export default {
    name: 'EnjoySelectDeptTree',
    props: {
        /* 外部v-model传入的部门 例如：v-model=[{id:1,name:'部门1'}] */
        value: {
            default: undefined,
        },
        /** 多选 默认不传为单选 */
        multiple: {
            type: Boolean,
        },
    },
    computed: {
        /** 多选值 [{userId:1,userName:'张三'},...] */
        multipleValue() {
            let multipleValue = []
            if (
                this.multiple &&
                Array.isArray(this.value) &&
                this.value.length > 0
            ) {
                multipleValue = this.value
            }
            return multipleValue
        },
        singleValue() {
            /** 单选 {userId:... userName:...} */
            let singleValue = {}
            if (!this.multiple && this.value) {
                const { id, name } = this.value
                if (id && name) {
                    singleValue = this.value
                }
            }
            return singleValue
        },
        defaultKeys() {
            let keys = undefined
            if (this.multiple) {
                if (this.value) {
                    keys = this.value.map((item) => `${item.id}`)
                } else {
                    keys = []
                }
            }
            return keys
        },
    },
    data() {
        return {
            visible: false,
            inputHeight: 32, //输入框高度
            data: undefined,
            defaultProps: {
                children: 'children',
                label: 'label',
            },
        }
    },
    watch: {
        visible(val) {
            if (val) {
                if (!this.data) {
                    this.getTreeData()
                }
            }
        },
    },
    mounted() {
        this.init()
    },
    methods: {
        init() {
            if (this.multiple) {
                const self = this
                /*多选时监听文本框内容高度*/
                const observer = new ResizeObserver((entries) => {
                    entries.forEach((entry) => {
                        const cr = entry.contentRect
                        self.inputHeight = (cr.height || 24) + 8
                    })
                })
                observer.observe(self.$refs.el_select__tags)
            }
        },
        getTreeData() {
            treeselect().then((res) => {
                this.data = res.data
            })
        },
        handleNodeClick(data) {
            console.log(data)
            if (!data.children && !this.multiple) {
                this.visible = false
            }
            if (!this.multiple) {
                const value = { id: data.id, name: data.label }
                this.$emit('input', value)
                this.$emit('change', value)
            }
        },
        checkChange(obj, checked, hasChildrenChecked) {
            if (this.multiple && !obj.children) {
                const { value } = this
                const array = value || []
                const cur = { id: obj.id, name: obj.label }
                if (checked) {
                    array.push(cur)
                } else {
                    const index = findIndex(array, { name: obj.label })
                    if (index > -1) {
                        array.splice(index, 1)
                    }
                }
                this.$emit('input', array)
                this.$emit('change', array)
            }
        },
        remove(row, index) {
            this.$refs.deptTree.setChecked(row.id, false)
        },
    },
}
</script>

<style scoped>
.head-folder-icon {
    display: flex;
    justify-content: center;
    align-items: center;
}
.head-folder-icon img {
    width: 15px;
    height: 15px;
    margin-right: 2px;
}
</style>
<style>
.popper-style {
    width: 300px !important;
}
</style>
